import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ugrownews_flutter/utils/Toast.dart';
import 'package:ugrownews_flutter/utils/netutil/NetUtil.dart';
import 'package:ugrownews_flutter/utils/netutil/NewsNetUtil.dart';
import 'package:cached_network_image/cached_network_image.dart';

class FragmentMainLive extends StatefulWidget {
  @override
  _FragmentMainLiveState createState() {
    _FragmentMainLiveState _fragmentMainLiveState = _FragmentMainLiveState();
    _initData(_fragmentMainLiveState, 1, 10);
    return _fragmentMainLiveState;
  }
}

Future<dynamic> _initData(
    //初始化数据
    _FragmentMainLiveState _fragmentMainLiveState,
    int page,
    int pageSize) {
  print("FragmentMainLive _initData");
  Map<String, String> params = new Map();
  params["page"] = page.toString();
  params["pageSize"] = pageSize.toString();
  return new NewsNetUtil().getLivetList(params, (result, isCache) {
    _fragmentMainLiveState.isLoading = false;
    if (result is NetError) {
      return;
    } else {
      Map jsonResult = json.decode(result);
      String state = jsonResult["state"];
      if (state.isNotEmpty && state == "success") {
        if (_fragmentMainLiveState.mounted) {
          _fragmentMainLiveState.setState(() {
            List<dynamic> data = jsonResult["data"];
            if (page == 1) {
              _fragmentMainLiveState.data = data;
            } else {
              _fragmentMainLiveState.data.addAll(data);
            }
          });
        }
      }
    }
  });
}

class _FragmentMainLiveState extends State<FragmentMainLive>
    with AutomaticKeepAliveClientMixin {
  List<dynamic> data = new List();
  int page = 1;
  bool isLoading = false;

  ScrollController controller = new ScrollController();
  GlobalKey<EasyRefreshState> _easyRefreshKey =
      new GlobalKey<EasyRefreshState>();

  @override
  void initState() {
    super.initState();
    print("FragmentMainLive initState");
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return new Container(
      child: data.length > 0
          ? new EasyRefresh(
              key: _easyRefreshKey,
              onRefresh: _onRefresh,
              loadMore: _loadMore,
              child: new ListView.builder(
                controller: controller,
                padding: EdgeInsets.all(0),
                itemCount: data.length,
                itemBuilder: _buildItem,
              ),
            )
          : new Center(
              child: new GestureDetector(
                child: new Text("正在加载"),
                onTap: () {
                  _initData(this, page, 10);
                },
              ),
            ),
    );
  }

  Future<dynamic> _onRefresh() {
    if (!isLoading) {
      isLoading = true;
      page = 1;
      return _initData(this, page, 10);
    }
  }

  Future<dynamic> _loadMore() async {
    if (!isLoading) {
      isLoading = true;
      page++;
      return _initData(this, page, 10);
    }
  }

  Widget _buildItem(BuildContext context, int index) {
    String imagepath = data[index]["img"];
    String title = data[index]["title"];
    String liveState = data[index]["liveState"];
    switch (liveState) {
      case "0":
        liveState = "直播";
        break;
      case "1":
        liveState = "回放";
        break;
      case "2":
        liveState = "预告";
        break;
      case "3":
        liveState = "结束";
        break;
    }
    String startTime = data[index]["startTime"];
    String fakeQuantity = data[index]["fakeQuantity"];

    int quality = int.parse(fakeQuantity);
    if (quality > 10000) {
      fakeQuantity = ((quality / 10000).toInt()).toString() +
          "." +
          ((quality % 10000 / 1000).toInt()).toString() +
          "W";
    }

    startTime = startTime.substring(5, 7) +
        "月" +
        startTime.substring(8, 10) +
        "日" +
        startTime.substring(11, 17);

    String time = startTime + "   " + fakeQuantity;

    return new GestureDetector(
      child: new Container(
        height: ScreenUtil.getInstance().setWidth(610),
        width: ScreenUtil.screenWidthDp,
        child: new Stack(
          alignment: Alignment.bottomCenter,
          children: <Widget>[
            new CachedNetworkImage(
              imageUrl: imagepath,
              placeholder: (context, url) {
                return new Image.asset(
                  "images/image_loading1.png",
                  height: ScreenUtil.getInstance().setWidth(610),
                  width: ScreenUtil.screenWidthDp,
                  fit: BoxFit.fill,
                );
              },
              errorWidget: (context, url, builder) {
                return new Icon(Icons.error);
              },
              height: ScreenUtil.getInstance().setWidth(610),
              width: ScreenUtil.screenWidthDp,
              fit: BoxFit.fill,
            ),
            new Positioned(
              bottom: 0,
              child: new Image.asset(
                "images/bannerview_back.png",
                fit: BoxFit.fill,
                width: ScreenUtil.screenWidthDp,
                height: ScreenUtil.getInstance().setWidth(450),
              ),
            ),
            new Positioned(
              bottom: ScreenUtil.getInstance().setWidth(125),
              left: ScreenUtil.getInstance().setWidth(44),
              right: ScreenUtil.getInstance().setWidth(44),
              child: new Text(
                title,
                overflow: TextOverflow.ellipsis,
                softWrap: true,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: ScreenUtil.getInstance().setWidth(46),
                ),
                maxLines: 2,
              ),
            ),
            //最下边一行文字
            new Positioned(
              child: new Container(
                height: ScreenUtil.getInstance().setWidth(100),
                child: new Stack(
                  children: <Widget>[
                    //播放状态
                    new Positioned(
                      left: ScreenUtil.getInstance().setWidth(43),
                      child: new Text(
                        liveState,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: ScreenUtil.getInstance().setWidth(46),
                        ),
                        maxLines: 1,
                      ),
                    ),
                    //时间，人数
                    new Positioned(
                      right: ScreenUtil.getInstance().setWidth(43),
                      child: new Text(
                        time,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: ScreenUtil.getInstance().setWidth(46),
                        ),
                        maxLines: 1,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        Toast.toast(context, data[index]["title"]);
      },
    );
  }

  @override
  bool get wantKeepAlive => true;
}
